<template>
  <div class="academic-evaluation">
    <el-tabs v-model="activeTab" @tab-click="handleTabClick">
      <el-tab-pane label="收到的评价" name="received">
        <div class="evaluation-list">
          <el-table
            v-loading="loading"
            :data="evaluationList"
            style="width: 100%">
            <el-table-column
              prop="userName"
              label="评价人"
              width="180">
            </el-table-column>
            <el-table-column
              prop="content"
              label="评价内容">
            </el-table-column>
            <el-table-column
              label="评分"
              width="180">
              <template slot-scope="scope">
                <el-rate
                  v-model="scope.row.score"
                  disabled
                  show-score>
                </el-rate>
              </template>
            </el-table-column>
            <el-table-column
              prop="createTime"
              label="评价时间"
              width="180">
              <template slot-scope="scope">
                {{ formatTime(scope.row.createTime) }}
              </template>
            </el-table-column>
            <el-table-column
              fixed="right"
              label="操作"
              width="120">
              <template slot-scope="scope">
                <el-button
                  type="text"
                  size="small"
                  @click="handleDelete(scope.row)"
                  style="color: #F56C6C;">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-size="pageSize"
            :total="total"
            layout="total, prev, pager, next"
            class="pagination">
          </el-pagination>
        </div>
      </el-tab-pane>
      
      <el-tab-pane label="发出的评价" name="sent">
        <div class="evaluation-list">
          <div class="operation-bar">
            <el-button type="primary" @click="showAddDialog">
              添加评价
            </el-button>
          </div>
          
          <el-table
            v-loading="loading"
            :data="evaluationList"
            style="width: 100%">
            <el-table-column
              prop="userName"
              label="被评价人"
              width="180">
            </el-table-column>
            <el-table-column
              prop="content"
              label="评价内容">
            </el-table-column>
            <el-table-column
              label="评分"
              width="180">
              <template slot-scope="scope">
                <el-rate
                  v-model="scope.row.score"
                  disabled
                  show-score>
                </el-rate>
              </template>
            </el-table-column>
            <el-table-column
              prop="createTime"
              label="评价时间"
              width="180">
              <template slot-scope="scope">
                {{ formatTime(scope.row.createTime) }}
              </template>
            </el-table-column>
            <el-table-column
              fixed="right"
              label="操作"
              width="120">
              <template slot-scope="scope">
                <el-button
                  type="text"
                  size="small"
                  @click="handleDelete(scope.row)"
                  style="color: #F56C6C;">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-size="pageSize"
            :total="total"
            layout="total, prev, pager, next"
            class="pagination">
          </el-pagination>
        </div>
      </el-tab-pane>
    </el-tabs>

    <!-- 删除确认对话框 -->
    <el-dialog
      title="提示"
      :visible.sync="deleteDialogVisible"
      width="30%">
      <span>确定要删除这条评价吗？</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="deleteDialogVisible = false">取 消</el-button>
        <el-button type="danger" @click="confirmDelete">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 添加评价对话框 -->
    <el-dialog
      title="添加评价"
      :visible.sync="dialogVisible"
      width="500px">
      <el-form :model="evaluationForm" :rules="rules" ref="evaluationForm" label-width="100px">
        <el-form-item label="被评价人" prop="toUserId">
          <el-select v-model="evaluationForm.toUserId" placeholder="请选择被评价人">
            <el-option
              v-for="user in userList"
              :key="user.id"
              :label="user.name"
              :value="user.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="评分" prop="score">
          <el-rate
            v-model="evaluationForm.score"
            show-score>
          </el-rate>
        </el-form-item>
        <el-form-item label="评价内容" prop="content">
          <el-input
            type="textarea"
            :rows="4"
            placeholder="请输入评价内容"
            v-model="evaluationForm.content">
          </el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitEvaluation">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'AcademicEvaluation',
  data() {
    return {
      activeTab: 'received',
      loading: false,
      evaluationList: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      dialogVisible: false,
      userList: [],
      evaluationForm: {
        toUserId: '',
        score: 0,
        content: ''
      },
      rules: {
        toUserId: [
          { required: true, message: '请选择被评价人', trigger: 'change' }
        ],
        score: [
          { required: true, message: '请给出评分', trigger: 'change' }
        ],
        content: [
          { required: true, message: '请输入评价内容', trigger: 'blur' },
          { min: 1, max: 500, message: '长度在 1 到 500 个字符', trigger: 'blur' }
        ]
      },
      deleteDialogVisible: false,
      currentDeleteId: null
    }
  },
  created() {
    this.fetchEvaluationList()
    this.fetchUserList()
  },
  methods: {
    handleTabClick() {
      this.currentPage = 1
      this.fetchEvaluationList()
    },
    handleCurrentChange(page) {
      this.currentPage = page
      this.fetchEvaluationList()
    },
    formatTime(time) {
      if (!time) return ''
      return time.split('T')[0]
    },
    fetchEvaluationList() {
      this.loading = true
      const type = this.activeTab === 'received' ? '0' : '1'
      
      this.$axios.get('/message/list', {
        params: {
          type,
          page: this.currentPage,
          pageSize: this.pageSize
        }
      }).then(res => {
        if (res.code === 200) {
          this.evaluationList = res.data
          this.total = res.total || res.data.length
        } else {
          this.$message.error(res.msg || '获取评价列表失败')
        }
      }).catch(err => {
        console.error('获取评价列表失败:', err)
        this.$message.error('获取评价列表失败')
      }).finally(() => {
        this.loading = false
      })
    },
    fetchUserList() {
      console.log('开始获取被评价人列表')
      this.$axios.get('/message/listByRecruitUnitId')
        .then(res => {
          console.log('获取被评价人列表响应:', res)
          if (res.code === 200) {
            this.userList = res.data.map(user => ({
              id: user.id,
              name: user.name
            }))
            console.log('处理后的用户列表:', this.userList)
          } else {
            this.$message.error(res.msg || '获取用户列表失败')
          }
        })
        .catch(err => {
          console.error('获取用户列表失败:', err)
          console.error('错误详情:', err.response || err)
          this.$message.error('获取用户列表失败')
        })
    },
    showAddDialog() {
      console.log('点击添加评价按钮')
      this.evaluationForm = {
        toUserId: '',
        score: 0,
        content: ''
      }
      console.log('当前用户列表长度:', this.userList.length)
      if (this.userList.length === 0) {
        console.log('用户列表为空，开始获取用户列表')
        this.fetchUserList()
      }
      this.dialogVisible = true
    },
    submitEvaluation() {
      this.$refs.evaluationForm.validate(valid => {
        if (valid) {
          this.$axios.post('/message/add', {
            toUserId: this.evaluationForm.toUserId,
            score: this.evaluationForm.score,
            content: this.evaluationForm.content,
            type: '1'
          }).then(res => {
            if (res.code === 200) {
              this.$message.success('评价提交成功')
              this.dialogVisible = false
              this.fetchEvaluationList()
            } else {
              this.$message.error(res.msg || '评价提交失败')
            }
          }).catch(err => {
            console.error('评价提交失败:', err)
            this.$message.error('评价提交失败')
          })
        }
      })
    },
    handleDelete(row) {
      this.currentDeleteId = row.id
      this.deleteDialogVisible = true
    },
    confirmDelete() {
      if (!this.currentDeleteId) return

      this.$axios.delete(`/message/${this.currentDeleteId}`)
        .then(res => {
          if (res.code === 200) {
            this.$message.success('删除成功')
            this.fetchEvaluationList()
          } else {
            this.$message.error(res.msg || '删除失败')
          }
        })
        .catch(err => {
          console.error('删除失败:', err)
          this.$message.error('删除失败')
        })
        .finally(() => {
          this.deleteDialogVisible = false
          this.currentDeleteId = null
        })
    }
  }
}
</script>

<style lang="scss" scoped>
.academic-evaluation {
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
  min-height: 500px;
  
  .evaluation-list {
    margin-top: 20px;
  }
  
  .pagination {
    margin-top: 20px;
    text-align: right;
  }

  .operation-bar {
    margin-bottom: 20px;
  }
  
  .el-rate {
    margin-top: 8px;
  }

  .el-button--text {
    padding: 0;
    &:hover {
      color: #ff4d4f;
    }
  }
}
</style> 